<!--
 * @Author: your name
 * @Date: 2021-10-15 23:14:28
 * @LastEditTime: 2021-10-18 13:29:00
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue_test3\src\components\power\Roles.vue
-->
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
        <!-- 添加角色按钮 -->
        <el-row>
            <el-col :span="1">
                <el-button type="primary" @click="addRolesDialogVisible = true">添加角色</el-button>
            </el-col>
        </el-row>

        <!-- 角色列表区域 -->
        <el-table :data="rolelist" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand" label="↓↓↓">
                <template v-slot="scope">
                    <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1)  in scope.row.children" :key="item1.id">
                        <!-- 渲染一级权限 -->
                        <el-col :span="5">
                            <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <!-- 渲染二级和三级权限 -->
                        <el-col :span="19">
                            <!-- 通过for循环前提渲染二级权限 -->
                            <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"  v-for="(item2,i2) in item1.children" :key="item2.id">
                                <el-col :span="6">
                                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <el-col :span="13">
                                    <el-tag type="warning"  v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                </el-col>

                            </el-row>
                            

                        </el-col>

                    </el-row>


                    <!-- <pre>
                        {{scope.row}}
                    </pre> -->
                </template>



            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="ID"></el-table-column>
            <el-table-column label="角色名称" prop="roleName"></el-table-column>
            <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
            <el-table-column label="操作">
                <template v-slot="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditRolesDialog(scope.row.id)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRolesById(scope.row.id)">删除</el-button>
                    <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>

            <!-- 分配权限的对话框 -->
        <el-dialog
        title="分配权限"
        :visible.sync="SetRightDialogVisible"
        width="50%"
        @close="setRightDialogClosed"
        >
        <!-- 树形控件 -->
        <el-tree :data="rightslist" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="reftree"></el-tree>
        <span slot="footer" class="dialog-footer">
            <el-button @click="SetRightDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
        </el-dialog>


        <!-- 编辑角色对话框 -->
         <!-- 修改用户的对话框 -->
            <el-dialog
            title="编辑用户"
            :visible.sync="editRightDialogVisible"
            width="30%"
            >
            <el-form :model="editRightForm" :rules="editRightFormRules" ref="editRightFormRef" label-width="100px" :status-icon="true">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRightForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRightForm.roleDesc"></el-input>
                </el-form-item>
               
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRolesUser">确 定</el-button>
            </span>
            </el-dialog>

        <!-- 添加用户的对话框 -->
        <el-dialog
        title="添加用户"
        :visible.sync="addRolesDialogVisible"
        width="50%" >
            <!-- 内容主体区域 -->
            <el-form :model="addRolesForm"  ref="addRolesFormRef" label-width="100px" :status-icon="true">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRolesForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRolesForm.roleDesc"></el-input>
                </el-form-item>
               
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addRolesDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRolesUser">确 定</el-button>
            </span>
        </el-dialog>

  </div>
</template>

<script>
export default {
    data() {
        return {
            //所有角色列表数据
            rolelist:[],
            //控制分配权限的对话框的展示和隐藏
            SetRightDialogVisible:false,
            //发起获取权限,存储下来
            rightslist:[],
            //树形控件的属性绑定对象
            treeProps:{
                children: 'children',
                label: 'authName'    
            },
            //默认选中的节点ID值
            defKeys:[],
            //分配权限的角色ID
            roleId:'',

            //控制编辑权限对话框的展示和隐藏
            editRightDialogVisible:false,

            //查询到的用户的信息对象
            editRightForm:{},

            //定义修改用户对话框的表单规则
            editRightFormRules:{
            roleName:[
                { required: true, message: '角色名称', trigger: 'blur' }
            ],
            roleDesc:[
                { required: true, message: '角色描述', trigger: 'blur' },
            ]
            },

            //   控制添加用户框的显示和隐藏
            addRolesDialogVisible:false,

            //添加用户的表单数据
            addRolesForm:{
                roleName:'',
                roleDesc:'',
            },
            // //添加用户的表单数据规则
            // addRolesFormRules:{
            //     roleName:[
            //         { required: true, message: '请输入角色名称', trigger: 'blur' },
            //         { min: 3, max: 15, message: '长度在 3 到 15个字符 ', trigger: 'blur' }
            //     ],
            //     roleDesc:[
            //     { required: true, message: '请输入角色描述', trigger: 'blur' }
            // ]
            // },

        }
    },
    created(){
        this.getRolesList()
    },
    methods:{
        //获取所有权限列表
        async getRolesList(){
            const {data:res} =  await this.$http.get('roles')
           if (res.meta.status !== 200) {
                this.$message.error("获取权限失败")
            } else {
                this.rolelist = res.data
                // console.log(this.rolelist)
            }

        },
        // 根据ID删除对应的权限
        async removeRightById(r,g){
            // 弹窗提示是否删除
          await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                    });          
                });    

              const {data:res} =await this.$http.delete(`roles/${r.id}/rights/${g}`)
            // console.log(res)
            if(res.meta.status !== 200){
                return this.$message.error('删除用户失败')
            }else{
                this.$message.success("删除用户成功")
                 //刷新用户表
                // this.getRolesList() 
                //吧服务器最新的权限直接赋值
                r.children = res.data       
            }    
        },
        //展示分配权限的对话框
        async showSetRightDialog(role){
            // 将分配角色的ID保存
            this.roleId= role.id
            //获取所有权限的处理
           const {data:res} =  await this.$http.get('rights/tree')
           if (res.meta.status !==200) {
               return this.$message.error("获取权限失败")
           } else {
               this.rightslist = res.data
                // console.log(this.rightslist)
                // 递归获取三级节点的ID
                this.getLeafKeys(role,this.defKeys)
              
           }
           this.SetRightDialogVisible = true  
        },

        //通过递归的形式,获取角色下所有三级权限的ID,并保持到defkeys数组中
        getLeafKeys(node,arr){
            //如果当前node节点不包含children属性,则是三级节点
            if (!node.children) {
                return arr.push(node.id)
            } else {
                node.children.forEach(element => {
                    this.getLeafKeys(element,arr)
                });
            }


        },
        //监听分配权限的关闭事件
        setRightDialogClosed(){
            this.defKeys =[]
        },

        //点击为角色分配权限
        async allotRights(){
            const keys=[
                ...this.$refs.reftree.getCheckedKeys(),
                ...this.$refs.reftree.getHalfCheckedNodes()
            ]
            //将数组拼接为字符串
            const strId = keys.join(',')
            
            const {data:res} =  await this.$http.post(`roles/${this.roleId}/rights`,{rids:strId})
            if (res.meta.status !==200) {
               return this.$message.error("分配权限失败")
           } else {
               this.$message.success("分配权限成功")
                 
                // console.log(this.rightslist)
                // 递归获取三级节点的ID
              
           }
           
             this.getRolesList()
             this.SetRightDialogVisible = false    
        },

        //角色删除
        async removeRolesById(id){
            // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete('roles/' + id)

      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }

      this.$message.success('删除用户成功！')
      //刷新用户表
           this.getRolesList()
        },

        //编辑角色
        editRolesUser(){
        this.$refs.editRightFormRef.validate(async valid=>{
           if (!valid) {
               return
           }else{
            //    console.log('什么问题')
               //发起修改用户的网络请求
            const {data:res} =  await  this.$http.put("roles/"+this.editRightForm.roleId,{roleName:this.editRightForm.roleName,roleDesc:this.editRightForm.roleDesc})
            if (res.meta.status !== 200) {
                this.$message.error("更新用户失败")
            } else {
                //隐藏添加用户的对话框
                this.editRightDialogVisible = false
                //刷新用户表
                this.getRolesList()
                this.$message.success("更新用户成功")
                
            }

           }
        })
        },

          //展示编辑用户的对话框
    async showEditRolesDialog(id){
        // console.log(id)
       const { data: res } = await this.$http.get('roles/'+id)
        if (res.meta.status !== 200) {
        return this.$message.error("查询用户信息失败")
      } else {
          this.editRightForm = res.data
        // this.$message.success("更新状态成功")
        this.editRightDialogVisible  = true
      }
        
    },

    
            //点击确定按钮,添加新用户
            addRolesUser(){
            // console.log(this)
            this.$refs.addRolesFormRef.validate(async valid=>{
            if (!valid) {
                return
            }else{
                //发起添加用户的网络请求
                const {data:res} =  await  this.$http.post("roles",this.addRolesForm)
                if (res.meta.status !== 201) {
                    this.$message.error("添加角色失败")
                } else {
                    this.$message.success("添加角色成功")
                    //隐藏添加用户的对话框
                    this.addRolesDialogVisible = false
                    //刷新用户表
                    this.getRolesList()
                }

            }
            })

        }    
    }
}
</script>

<style lang="less" scoped>
.el-tag{
    margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}

</style>